<?php

namespace Lowpress\PressExtensionsBundle\Feeds;

use Lowpress\PressBundle\Feeds\IFeedGatherer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Lowpress\PressExtensionsBundle\Entity\Tweet;

class TwitterFeedGatherer implements IFeedGatherer
{


  private $api_url;

  public function __construct($api_url)
  {
    $this->api_url = $api_url;
  }

  public function gather(ContainerInterface $container)
  {
    $api_url = $this->api_url;

    $doctrine = $container->get("doctrine");
    $tweet_repository = $doctrine->getRepository('LowpressPressExtensionsBundle:Tweet');
    $em = $doctrine->getEntityManager();

    // get the last tweet inserted
    if ($last_tweet = $tweet_repository->findOneBy(array(), array('created', 'DESC')))
    {
      // append the date to the api url
      $api_url .= "+since:".$last_tweet->getCreated()->format('Y-m-d');
    }

    // get the json file
    $json = json_decode(file_get_contents($api_url));

    // for each of the results
    foreach ($json->results as $result)
    {
      // get the date
      $created_at = new \DateTime($result->created_at);

      // if there's not a tweet in the database, or if there IS a tweet, check the date is bigger than the previously entered tweet
      if (!$last_tweet || ($last_tweet && $created_at > $last_tweet->getCreated()))
      {
        $tweet = new Tweet();
        $tweet->setText($result->text);
        $tweet->setFromUser($result->from_user);
        $tweet->setProfileImage($result->profile_image_url);
        $tweet->setCreated(new \DateTime($result->created_at));

        preg_match_all("/(?:^|\s)#(\w+)/", $result->text, $out, PREG_PATTERN_ORDER);

        if (isset($out) && isset($out[1]))
        {
          foreach ($out[1] as $tag_name)
          {
            $tag = $doctrine->getRepository('LowpressPressBundle:Tag')->findOneByName($tag_name);
            if ($tag == null)
            {
              $tag = new \Lowpress\PressBundle\Entity\Tag();
              $tag->setName($tag_name);
              $tweet->addTag($tag);
            }
            $em->persist($tag);
          }
        }
        $em->persist($tweet);
      }
    }
    $em->flush();
  }

}

?>